package com.xiaxiang.xiawan.share;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dg.acb.utils.configdata.XXConstants;
import com.donggua.client.fileserverlibrary.FileServerUpload;
import com.okhttp.MyHttpUtils;
import com.third.login.ThirdLoginPlatform;
import com.third.share.ShareData;
import com.vondear.rxtools.view.dialog.RxDialogLoading;
import com.xiaxiang.ar.ARCloud.ARCloudEditor;
import com.xiaxiang.xiawan.FunPhoto.FunPhotoCreate;
import com.xiaxiang.xiawan.Home.HomeData;
import com.xiaxiang.xiawan.R;
import com.xiaxiang.xiawan.Util.XXToolUtil;
import com.xiaxiang.xiawan.XXConfigData;
import com.xiaxiang.xiawan.XXMainApplication;
import com.xiaxiang.xiaxwan.ar.data.XXARMaterialVideoData;
import com.xx.xiawan.net.DGJsonRequest;
import com.xx.xiawan.net.DGJsonResult;
import com.xx.xiawan.net.DGNetUtil;
import com.xx.xiawan.net.DGRequestBase;
import com.xx.xiawan.net.DGRequestListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by Administrator on 2017-10-27.
 */
// com.xiaxiang.xiawan.share.ShareAndUploadActivity
public class ShareAndUploadActivity extends Activity implements View.OnClickListener{
    private final static String TARGET_NAME_KEY = "targetName";
    private final static String MATERIAL_ID_KEY = "materialId";
    private final static String MATERIAL_URL_KEY = "materialUrl";
    private final static String USER_NAME_KEY = "userName";
    private final static String NAME_KEY = "name";
    private final static String PIC_FILE_NAME_KEY = "picFileName";
    private final static String VIDEO_FILE_NAME_KEY = "videoUrl";
    private final static String shareUrl = "shareUrl";
    final  public static int RES_CODE = 0x90;
    private final int MSG_DIALOG_HIDE = 0x01;
    private final int MSG_DIALOG_SHOW = 0x02;
    private final int MSG_RES_SUCCESS = 0x10;
    private final int MSG_RES_ERROR = 0x11;
    private final int MSG_TIP = 0x30;
    private RxDialogLoading dialogLoading;
    private String mPicFilePath = "";
    private String mVideoFilePath = "";
    private Handler mUiHandler = null;
    private MyShareOperator mShareOperator;
    private final static String POST_URL = XXConstants.HTTP_GET_SAVE_MATERIAL_VIDEO;
    //"http://121.196.213.86:8089/video/saveMaterialVideo"
    private ImageView imgUpload;
    private File mUploadFile;
    private XXARMaterialVideoData mMaterialData;
    private String mTargetName = "";
    private EditText etShare;
    public final static int LOAD_PIC = 1001;
    protected boolean mIsCanShare = true;
    protected XXMainApplication mMainApplication;
    public void onCreate(Bundle bundle){
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(bundle);
        View mainView = LayoutInflater.from(this).inflate(R.layout.share_and_issu,null);
        setContentView(mainView);
        Intent intent = getIntent();
        if(intent != null){
            mMaterialData = intent.getParcelableExtra(XXToolUtil.MATERIAL_VIDEO_DATA_KEY);
            if(mMaterialData != null){
                mPicFilePath = intent.getStringExtra(PIC_FILE_NAME_KEY);
                mVideoFilePath = mMaterialData.mVideoPath;
            }
        }
        dialogLoading = new RxDialogLoading(this);
        if(mMaterialData != null){
            Log.e("up"," ShareAndUploadActivity mMaterialId is "+mMaterialData.mMaterialId);
            Log.e("up"," ShareAndUploadActivity mMaterialUrl is "+mMaterialData.mMaterialUrl);
            Log.e("up"," ShareAndUploadActivity mUserName is "+mMaterialData.mUserName);
            Log.e("up"," ShareAndUploadActivity mName is "+mMaterialData.mName);
        }
        ImageView imgBack = (ImageView)findViewById(R.id.imgBack);
        imgBack.setOnClickListener(this);
        TextView btnIssu = (TextView)findViewById(R.id.btnIssu);
        btnIssu.setOnClickListener(this);
        setHandler();
        imgUpload = (ImageView)findViewById(R.id.imgUpload);
        etShare = (EditText)findViewById(R.id.et_share);
        if(mPicFilePath != null && mPicFilePath.length() != 0){

        }
        new Thread(){
            public void run(){
                super.run();
                Bitmap bitmap = createVideoThumbnail(mVideoFilePath);
                String cachePath = XXConfigData.getCachePath();
                mPicFilePath= cachePath+System.currentTimeMillis()+".jpg";
                saveBitmapFile(bitmap,mPicFilePath);
                bitmap.recycle();
                sendMessage(LOAD_PIC,"");
            }
        }.start();
        mShareOperator = new MyShareOperator(this,mainView);
        mMainApplication = (XXMainApplication) getApplication();
        mMainApplication.initUserInfo();
    }

    public void saveBitmapFile(Bitmap bitmap,String path){
        File file=new File(path);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void setHandler(){
        mUiHandler = new Handler(){
          public void handleMessage(Message msg){
              super.handleMessage(msg);
              switch (msg.what){
                  case LOAD_PIC:
                    File file = new File(mPicFilePath);
                    final WeakReference<ImageView> imageViewWeakReference = new WeakReference<ImageView>(imgUpload);
                    ImageView weekImage = imageViewWeakReference.get();
                    Glide.with(getApplicationContext()).load(Uri.fromFile(file)).into(weekImage);
                      break;
                  case  MSG_DIALOG_HIDE:
                      if(dialogLoading.isShowing()){
                          dialogLoading.hide();
                      }
                      break;

                  case  MSG_DIALOG_SHOW:
                      dialogLoading.show();
                      break;

                  case MSG_TIP:
                      String text = (String) msg.obj;
                      Toast.makeText(getActivity(),text,Toast.LENGTH_SHORT).show();
                  break ;
              }
          }
        };
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id){
            case R.id.imgBack:
                finish();
              break;
            case R.id.btnIssu:
                String shareName = etShare.getText().toString();
                if(shareName != null && shareName.length() >0) {
                    uploadVideoData();
                }else {
                    Log.i("up","name is null");
                    sendMessage(MSG_TIP,"名称不能为空！");
                }
                break;
            default:
                mShareOperator.onClick(view);
                break;
        }
    }

    //上传视频
    private void uploadVideoData(){
        sendMessage(MSG_DIALOG_SHOW,"");
        FileServerUpload fileServerUpload = new FileServerUpload(this);
        fileServerUpload.setOnUploadSuccess(new FileServerUpload.IUploadComplete() {
            public void onUploadSuccess(String fileKey, String fileHash, int code) {
                Log.e("up"," uploadVideoData is "+fileKey);
                mTargetName = fileKey;
            //    uploadData();//视频成功后，上传图片
                startPostRequest(mTargetName);//图片上传成功后，上传数据到服务器
                sendMessage(MSG_DIALOG_HIDE,"");
            }

            @Override
            public void onUploadFail(String errorMsg, int code) {
                if(code == DGNetUtil.REQUEST_NEED_LOGIN){
                    XXConfigData.startLoginActivity(ShareAndUploadActivity.this);
                }
                Log.e("up"," uploadVideoData errorMsg is "+errorMsg+" error code is "+code);
                sendMessage(MSG_DIALOG_HIDE,"");
            }
        });
        fileServerUpload.uploadPublic(mVideoFilePath, 0,mMainApplication.getToken());
    }
    private void uploadData(){
        FileServerUpload fileServerUpload = new FileServerUpload(this);
//        fileServerUpload.uploadPublic(mPicFilePath, 0);
        fileServerUpload.setOnUploadSuccess(new FileServerUpload.IUploadComplete() {
            public void onUploadSuccess(String fileKey, String fileHash, int code) {
                //photoName = fileKey;
                String photoName = fileKey;
              //  Log.i("drj", "compressWithLs: code: " + code + " fileKey: " + fileKey + " fileHash:" + fileHash);
                startPostRequest(mTargetName);//图片上传成功后，上传数据到服务器
                File file = new File(mPicFilePath);
                file.deleteOnExit();
            }

            @Override
            public void onUploadFail(String errorMsg, int code) {

            }
        });
    }

    private void startPostRequest(String photoName){
        JSONObject jsonObject = new JSONObject();

        try {
            File file = new File(mVideoFilePath);
            String name = file.getName();
            jsonObject.put(TARGET_NAME_KEY,photoName);
            jsonObject.put(NAME_KEY,etShare.getText().toString());
            jsonObject.put(USER_NAME_KEY,mMainApplication.getUserName());
            if(mMaterialData != null){
                jsonObject.put(MATERIAL_ID_KEY,mMaterialData.mMaterialId);
                jsonObject.put(MATERIAL_URL_KEY,mMaterialData.mMaterialUrl);

            }else{
                jsonObject.put(MATERIAL_ID_KEY,0);
                jsonObject.put(MATERIAL_URL_KEY,"");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("up"," jsonObject is "+jsonObject.toString());
        DGRequestListener listener = new DGRequestListener() {
            @Override
            public void onSuccess(DGJsonResult result) {
                Log.e("up"," result is "+result.result+" mIsCanShare is "+mIsCanShare);
                if(!mIsCanShare){
                    return;
                }
                try {
                    JSONObject object = new JSONObject(result.result);
                    HomeData homeData = new HomeData();
                    homeData.setJSONData(object);
                    ShareData shareData = new ShareData();
                    shareData.mShareUrl =homeData.mShareUrl;
                    shareData.mThumbFileUrl = mPicFilePath;
                    shareData.mShareThumbStyle = ShareData.IMG_LOCAL_FILE;
                  //  shareData.mBitmap =mPicFilePath;
                   // shareData.mShareTitle = etShare.getText().toString();
                    shareData.mShareTitle  = getString(R.string.ar_video);
                    shareData.mShareStyle = ShareTest.VIDEO11;
                    mShareOperator.setShareData(shareData);
                    mShareOperator.startShare();
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String error) {
                Log.e("up"," onError is "+error);
            }
        };
        MyHttpUtils myHttpUtils = new MyHttpUtils();
        try {
            myHttpUtils.PostAsync(POST_URL,jsonObject.toString(),mMainApplication.getToken(),listener);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        DGJsonRequest request = new DGJsonRequest(ShareAndUploadActivity.this,POST_URL,jsonObject,listener);
//        request.header(XXConfigData.TOKEN_KEY,mMainApplication.getToken());
//        request.startNoLock();
    }
    private void compressWithLs(final File photos) {
        Luban.with(this.getApplicationContext())
                .load(photos)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        final WeakReference<ImageView> imageViewWeakReference = new WeakReference<ImageView>(imgUpload);
                        ImageView weekImage = imageViewWeakReference.get();
                        Glide.with(getApplicationContext()).load(Uri.fromFile(file)).into(weekImage);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();
    }

    private class MyShareOperator extends XXShareOperator{
        private ThirdLoginPlatform mPlatform;
        public MyShareOperator(Context context, View mainView) {
            super(context, mainView);
            onCreate(null);
            setOnClickListener(ShareAndUploadActivity.this);
        }

        public void onCreate(Bundle bundle){
            super.onCreate(bundle);
            tvWxcircleShare.setImagePic(mSelectPicIdList[0]);
            mSelectThirdShareItem = tvWxcircleShare;
            mPlatform = ThirdLoginPlatform.WEIXIN_CIRCLE;
        }

        protected  void clickSameView(View view){
            if(mSelectList[mSelectIndex]){
                mIsCanShare = true;
                mSelectThirdShareItem.setImagePic(mSelectPicIdList[mSelectIndex]);
            }else{
                mIsCanShare = false;
                mSelectThirdShareItem.setImagePic(mPicIdList[mSelectIndex]);
            }
        }

        private void startShare(){
             if(mShareData != null && mPlatform != null && mIsCanShare){
                 mShareData.mThirdSharePlatform = mPlatform;
                 switch (mShareData.mThirdSharePlatform){
                     case QQ:
                         initQQ();
                         mQQShare.thirdShare(mShareData);
                         break;
                     case WEIXIN:
                         initWeiXin();
                         mWeiXinShare.thirdShare(mShareData);
                         break;
                     case WEIXIN_CIRCLE:
                         initWeiXin();
                         mWeiXinShare.thirdShare(mShareData);
                         break;
                     case QZONE:
                         initQQ();
                         mQQShare.thirdShare(mShareData);
                         break;
                     case SINA:
                         initSina();
                         mSinaShare.thirdShare(mShareData);
                         break;
                 }
             }

        }

        @Override
        protected void shareOperator(ThirdLoginPlatform platform) {
            mPlatform = platform;
        }
    }

    public void onDestroy(){
        super.onDestroy();
        DGRequestBase.quit(getApplicationContext());
        if(mPicFilePath != null && mPicFilePath.length() != 0){
            File file = new File(mPicFilePath);
            file.deleteOnExit();
        }
    }

    private Bitmap createVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
       //     retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime(1000);
        } catch(IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        return bitmap;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == XXConfigData.LOGIN_REQUEST_CODE){
            if(resultCode == XXConfigData.LOGIN_RECODE_SUCCESS){
                mMainApplication.initUserInfo();
                uploadVideoData();
            }
        }
    }

    private void sendMessage(int what, Object obj) {
        Message msg = mUiHandler.obtainMessage();
        msg.what = what;
        if (obj != null)
            msg.obj = obj;
        mUiHandler.sendMessage(msg);
    }

    private  Activity getActivity(){
        return this;
    }
}
